/*
 * Event.java
 *
 * Created on 10 de Julho de 2011, 17:04
 *
 */

package intopo.demonstrator;

import util.math.Rational;

import cern.jet.random.engine.MersenneTwister;

/**
 * Represents an event with its sucess probability.
 *
 * @author <a href="mailto:mariano.pedro@gmail.com">Pedro Mariano</a>
 *
 * @version 1.0 10 de Julho de 2011
 */
public class Event
	implements Cloneable
{
	private Rational probability;
	private float rawProbability;
	
	/**
	 * Construct a new Event.
	 */
	public Event (Rational probability)
	{
		setProbability (probability);
	}
	/**
	 * Construct a new Event.
	 */
	public Event (float rawProbability)
	{
		setRawProbability (rawProbability);
	}
	public Event (Event event)
	{
		this.rawProbability = event.rawProbability;
		this.probability = event.probability;
	}
	public Event clone ()
	{
		return new Event (this);
	}
	/**
	 * Return the raw probability of a sucessfull event.
	 */
	final public float getRawProbability ()
	{
		return this.rawProbability;
	}
	final public void setRawProbability (float rawProbability)
	{
		if (rawProbability < 0 || rawProbability > 1) {
			throw new IllegalArgumentException ("Probabilities must be greater or equal than 0 and less than or equal to 1");
		}
		this.rawProbability = rawProbability;
		this.probability = new Rational (rawProbability);
	}
	/**
	 * Return the probability of a sucessfull event as a rational number.
	 *
	 * <p> This method is used by the GUI components.  The user sees the
	 * probability as a rational number.  Internally the probability
	 * is represented by a floating point number.
	 */
	final public Rational getProbability ()
	{
		return probability;
	}
	/**
	 * Sets the probability of a sucessfull event.
	 *
	 * <p> This method is used by the GUI components.  The user sees the
	 * probability as a rational number.  Internally the probability
	 * is represented by a floating point number.
	 */
	final public void setProbability (Rational probability)
		throws IllegalArgumentException
	{
		if (probability.compareTo (Rational.ZERO) < 0
			 || probability.compareTo (Rational.ONE) > 0) {
			throw new IllegalArgumentException ("Probabilities must be greater or equal than 0 and less than or equal to 1");
		}
		this.probability = probability;
		this.rawProbability = probability.toBigDecimal ().floatValue ();
//		try {
//		}
//		catch (ArithmeticException e) {
//			this.rawProbability = probability.numerator ().floatValue ()
//				/ probability.denominator ().floatValue ();
//		}
	}
	/**
	 * Performs this event and return {@code true} if it was sucessfull
	 */
	final public boolean eventSucess (MersenneTwister supply)
	{
		return supply.raw () < getRawProbability ();
	}
	/**
	 * Return the sucess probability of this event as a string.
	 */
	public String toString ()
	{
		return this.probability.toString ();
	}
}

// Local Variables:
// mode: java
// mode: flyspell-prog
// ispell-local-dictionary: "british"
// End:
